/* 
 *
 * Persistence4J - Simple library for data persistence using java
 * Copyright (c) 2010, Avdhesh yadav.
 * http://www.avdheshyadav.com
 * Contact: avdhesh.yadav@gmail.com
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */

package com.avdy.p4j.jdbc.dao.util;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import java.util.List;
import java.util.Map;


import org.apache.log4j.Logger;


import com.avdheshyadav.dbcrawler.dbmodel.Column;
import com.avdy.p4j.jdbc.common.JdbcSqlUtil;
import com.avdy.p4j.jdbc.dbms.metadata.TableStructure;
import com.avdy.p4j.jdbc.model.DTO;
import com.avdy.p4j.jdbc.service.GenericDTO;


/**
 * 
 * @author Avdhesh Yadav
 *
 */
public class PersistenceUtil 
{
	static Logger logger = Logger.getLogger(PersistenceUtil.class.getName());
	
	/**
	 * This method copies the data to the PreparedStatement.this is simply copy method without involving any Reflection so it is very fast.
	 * 
	 * @param tableStructure TableStructure
	 * @param valueObject DTO
	 * @param pstmt PreparedStatement
	 */
	public static void copyEntityObjectToPstmt(TableStructure tableStructure ,DTO valueObject, PreparedStatement pstmt)throws SQLException,Exception
	{
		List<Column> columns = tableStructure.getColumns();
		GenericDTO gvo = (GenericDTO)valueObject;
		
		Map<String, Object> data = gvo.getData();
		
		for(Column column : columns)
		{
			String columnName = column.getColumnName();
			columnName = columnName.toLowerCase();
			Object obj = data.get(columnName);
			int columnType = column.getDataType().getType();
			
			if(obj != null || column.isNullable())
			{
				JdbcSqlUtil.javaToSql(columnType, column.getOrdinalPosition(), obj, pstmt);
			}
			else
			{
				logger.error("null value is not allowed for column: "+ columnName);
			}
		}
	}
}